/*
 * Wireless Transmitter
 *
 * Created: 12/12/2014 6:42:48 p.m.
 * Author: Tick
 */ 

#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>
#include "nrf24.h"

#define F_CPU = 8000000UL;

//TODO: assign_unit_address(uint8_t address)
//Function which stores assigned identifier into EEPROM

//TODO: status_change()
//Function which updates unit status on message receive

//TODO: Set ALL pins to OUTPUT mode and OFF to save power
//TODO: Disable ADC

int main(void)
{
	MCUCR &= (0<<4);
	nrf24_init();
	nrf24_config(1,1);	//Channel, payload length

	//TODO: Accommodate for protocol [address][payload][???]
	uint8_t command_array[1];	//Create container for commands

	uint8_t tx_address[5] = {0xE7,0xE7,0xE7,0xE7,0xE7};
	nrf24_tx_address(tx_address);

	uint8_t rx_address[5] = {0xD7,0xD7,0xD7,0xD7,0xD7};
	nrf24_rx_address(rx_address);
	
	uint8_t switch_state, old_switch_state;
	DDRD |= (1<<6);		//Set onboard LED to output mode
	DDRD &= ~(1<<0);		//Set D0 to input mode with internal pullup
	PORTD |= (1<<0);
	
	switch_state = (PIND & (1<<0));	//Read PinD0
	old_switch_state = switch_state;
	
	DDRC |= (1<<7);		//Set successful message send LED indicator to output mode
	PORTC &= ~(1<<7);	//Turn success LED OFF first
	
	//Perform a double blink to indicate it is working
	PORTD |= (1<<6);
	_delay_ms(500);
	PORTD &= ~(1<<6);
	_delay_ms(500);
	PORTD |= (1<<6);
	_delay_ms(500);
	PORTD &= ~(1<<6);
	//======

	
    while(1)
    {
		switch_state = (PIND & (1<<0));	//Read the switch state
		if(old_switch_state != switch_state)
		{
			command_array[0] = switch_state;
			nrf24_send(command_array);	//Send switch state to turn on/off light
			while(nrf24_isSending())	//Wait for shit to send
			{
				PORTD |= (1<<6);	//Turn onboard LED ON
			}
			if(nrf24_lastMessageStatus()==NRF24_TRANSMISSON_OK)
			{
				PORTC |= (1<<7);
				_delay_ms(500);
				PORTC &= ~(1<<7);
			}
			PORTD &= ~(1<<6);
		}
		old_switch_state = switch_state;
    }
	_delay_ms(500);
}